package org.ragdollcat.first.controller;

import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.ragdollcat.first.manager.auth.SpaceUserAuthManager;
import org.ragdollcat.first.common.BaseResponse;
import org.ragdollcat.first.common.DeleteRequest;
import org.ragdollcat.first.common.ResultUtils;
import org.ragdollcat.first.constants.UserConstant;
import org.ragdollcat.first.exception.ErrorCode;
import org.ragdollcat.first.exception.ThrowUtils;
import org.ragdollcat.first.mapper.SpaceMapper;
import org.ragdollcat.first.model.annotation.AuthCheck;
import org.ragdollcat.first.model.dto.space.SpaceAddRequest;
import org.ragdollcat.first.model.dto.space.SpaceEditRequest;
import org.ragdollcat.first.model.dto.space.SpaceQueryRequest;
import org.ragdollcat.first.model.dto.space.SpaceUpdateRequest;
import org.ragdollcat.first.model.entity.Space;
import org.ragdollcat.first.model.entity.User;
import org.ragdollcat.first.model.enums.SpaceLevelEnum;
import org.ragdollcat.first.model.enums.SpaceTypeEnum;
import org.ragdollcat.first.model.vo.SpaceLevel;
import org.ragdollcat.first.model.vo.SpaceVO;
import org.ragdollcat.first.service.SpaceService;
import org.ragdollcat.first.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/space")
public class SpaceController {

    @Resource
    private SpaceService spaceService;

    @Resource
    private UserService userService;

    @Resource
    private SpaceUserAuthManager spaceUserAuthManager;

    @Resource
    private SpaceMapper spaceMapper;

    /**
     * 所有用户都能创建空间
     * todo 管理员可以为指定用户创建空间
     *
     * @param spaceAddRequest
     * @param httpServletRequest
     * @return
     */
    @PostMapping("/createSpace")
    public BaseResponse<Long> createSpace(@RequestBody SpaceAddRequest spaceAddRequest, HttpServletRequest httpServletRequest) {
        ThrowUtils.throwIf(ObjUtil.isEmpty(spaceAddRequest), ErrorCode.PARAMS_ERROR);
        return ResultUtils.success(spaceService.createSpace(spaceAddRequest, httpServletRequest));
    }


    /**
     * 根据ID删除空间，管理员可以删除所有，用户只能删除自己的
     * todo 删除空间后，将对应空间内的所有图片全部清除
     *
     * @param deleteRequest
     * @return
     */
    @PostMapping("/deleteById")
    public BaseResponse<Boolean> deleteSpaceById(@RequestBody DeleteRequest deleteRequest, HttpServletRequest httpServletRequest) {
        ThrowUtils.throwIf(ObjUtil.isEmpty(deleteRequest), ErrorCode.PARAMS_ERROR);
        //校验要删除的空间是否存在
        Long id = deleteRequest.getId();
        Space space = spaceService.getById(id);
        ThrowUtils.throwIf(ObjUtil.isEmpty(space), ErrorCode.OPERATION_ERROR, "该空间不存在！");
        //权限校验
        Long userId = space.getUserId();
        User loginUser = userService.getLoginUser(httpServletRequest);
        ThrowUtils.throwIf(!loginUser.getUserRole().equals(UserConstant.ADMIN_ROLE) && !Objects.equals(loginUser.getId(), userId),
                ErrorCode.NO_AUTH_ERROR, "无权删除！");
        ThrowUtils.throwIf(!spaceService.removeById(id), ErrorCode.OPERATION_ERROR, "空间删除失败！");
        return ResultUtils.success(true);
    }


    /**
     * 管理员更新空间
     * 可以更新名称和级别
     *
     * @param spaceUpdateRequest
     * @return
     */
    @PostMapping("/admin/updateSpace")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> adminUpdateSpace(@RequestBody SpaceUpdateRequest spaceUpdateRequest, HttpServletRequest httpServletRequest) {
        ThrowUtils.throwIf(ObjUtil.isEmpty(spaceUpdateRequest), ErrorCode.PARAMS_ERROR);
        //校验要修改的空间是否存在
        Long id = spaceUpdateRequest.getId();
        Space space = spaceService.getById(id);
        ThrowUtils.throwIf(ObjUtil.isEmpty(space), ErrorCode.OPERATION_ERROR, "该空间不存在！");
        //更新参数校验
        spaceService.vaildUpdSpaceParam(spaceUpdateRequest.getSpaceName(),
                spaceUpdateRequest.getSpaceLevel(),
                userService.getLoginUser(httpServletRequest),
                spaceUpdateRequest.getSpaceType(), false);
        //更新空间
        Space updSpace = new Space();
        BeanUtils.copyProperties(spaceUpdateRequest, updSpace);
        ThrowUtils.throwIf(!spaceService.updateById(updSpace), ErrorCode.OPERATION_ERROR, "空间更新失败！");
        return ResultUtils.success(true);
    }

    /**
     * 用户修改空间，只能修改自己的
     * 不能自己修改级别和空间类型
     *
     * @param spaceEditRequest
     * @return
     */
    @PostMapping("/user/updateSpace")
    public BaseResponse<Boolean> userUpdateSpace(@RequestBody SpaceEditRequest spaceEditRequest, HttpServletRequest httpServletRequest
    ) {
        ThrowUtils.throwIf(ObjUtil.isEmpty(spaceEditRequest), ErrorCode.PARAMS_ERROR);

        //校验要修改的空间是否存在
        Long id = spaceEditRequest.getId();
        Space space = spaceService.getById(id);
        ThrowUtils.throwIf(ObjUtil.isEmpty(space), ErrorCode.OPERATION_ERROR, "该空间不存在！");
        //校验权限
        User loginUser = userService.getLoginUser(httpServletRequest);
        ThrowUtils.throwIf(!loginUser.getUserRole().equals(UserConstant.ADMIN_ROLE)
                && !space.getUserId().equals(loginUser.getId()), ErrorCode.NO_AUTH_ERROR, "无权操作！");
        //更新参数校验(用户不能自己修改级别)
        spaceService.vaildUpdSpaceParam(spaceEditRequest.getSpaceName(), null, loginUser, spaceEditRequest.getSpaceType(), false);
        //更新空间
        Space updSpace = new Space();
        BeanUtils.copyProperties(spaceEditRequest, updSpace);
        ThrowUtils.throwIf(!spaceService.updateById(updSpace), ErrorCode.OPERATION_ERROR, "空间更新失败！");
        return ResultUtils.success(true);
    }

    /**
     * 管理员查询空间管理页面
     *
     * @param spaceQueryRequest
     * @return
     */
    @PostMapping("/admin/spacePage")
    public BaseResponse<Page<Space>> adminSpacePage(@RequestBody SpaceQueryRequest spaceQueryRequest) {
        ThrowUtils.throwIf(ObjUtil.isEmpty(spaceQueryRequest), ErrorCode.PARAMS_ERROR);
        return ResultUtils.success(spaceService.getSpacePage(spaceQueryRequest));
    }

    /**
     * 用户查询空间管理页面
     *
     * @param spaceQueryRequest
     * @return
     */
    @PostMapping("/user/spacePage")
    public BaseResponse<Page<SpaceVO>> userSpacePage(@RequestBody SpaceQueryRequest spaceQueryRequest) {
        ThrowUtils.throwIf(ObjUtil.isEmpty(spaceQueryRequest), ErrorCode.PARAMS_ERROR);
        return ResultUtils.success(spaceService.getSpacePageVO(spaceQueryRequest));
    }

    /**
     * 根据id获取空间的详情信息
     *
     * @param id
     * @param httpServletRequest
     * @return
     */
    @GetMapping("/getSpaceById")
    public BaseResponse<Space> getSpaceById(Long id, HttpServletRequest httpServletRequest) {
        ThrowUtils.throwIf(ObjUtil.isEmpty(id), ErrorCode.PARAMS_ERROR);
        Space space = spaceService.getById(id);
        User loginUser = userService.getLoginUser(httpServletRequest);
//        ThrowUtils.throwIf(!loginUser.getUserRole().equals(UserConstant.ADMIN_ROLE)
//                && !space.getUserId().equals(loginUser.getId()), ErrorCode.NO_AUTH_ERROR, "无权操作！");
        //编程式权限校验
        space.setPremissionList(spaceUserAuthManager.getPermissionList(space, loginUser));
        return ResultUtils.success(space);
    }

    /**
     * 获取会员信息列表
     *
     * @return
     */
    @GetMapping("/spaceLevel")
    public BaseResponse<List<SpaceLevel>> querySpaceLevel() {
        return ResultUtils.success(Arrays.stream(SpaceLevelEnum.values()).map(
                spaceLevelEnum -> new SpaceLevel(spaceLevelEnum.getValue(),
                        spaceLevelEnum.getText(),
                        spaceLevelEnum.getMaxCount(),
                        spaceLevelEnum.getMaxSize())
        ).collect(Collectors.toList()));
    }

    @GetMapping("/getSpaceType")
    public BaseResponse<Integer> getSpaceTypeByPictureId(Long pictureId) {
        Integer result = spaceMapper.getSpaceTypeByPictureId(pictureId);
        return ResultUtils.success(result);
    }

}
